#!/bin/sh
# This is useful for debugging
#set -x

if [ "$1" = "-v" ]; then
    silent_make_flags=""
    shift
else
    silent_make_flags="-s LIBTOOLFLAGS=--silent"
fi
if [ -f /opt/csw/bin/gmake ]; then
    MAKE=/opt/csw/bin/gmake
else
    MAKE=make
fi

#### CHECKS
if [ ! -f common-src/amanda.h ]; then
    echo "Error: 'buildpkg' must be run from the root of an otherwise unused amanda source"
    echo " directory." >&2
    exit 1
fi

if [ ! -f configure ]; then
    echo "Error: The source directory has not been autogen'd -- please download a source"
    echo " distribution tarball or run ./autogen.  You will need autoconf, automake,"
    echo " and libtool to run autogen (but not to compile from a distribution tarball)."
    exit 1
fi

# Until we get package revisioning in community.
[ -f "PKG_REV" ] || echo "1" > PKG_REV

pkg_root=packaging/sun-pkg
get_version() {
    # Get our version using substitute.pl
    echo "%%VERSION%%" > ${pkg_root}/version.src
    /opt/csw/bin/perl packaging/common/substitute.pl ${pkg_root}/version.src ${pkg_root}/version || exit 1
    VERSION=`cat ${pkg_root}/version`
    rm ${pkg_root}/version.src ${pkg_root}/version || exit 1
}

do_substitution() {
    file_list="client/pkginfo \
        client/preinstall \
        client/postinstall \
        client/postremove \
        server/pkginfo \
        server/preinstall \
        server/postinstall \
        server/postremove"
    for file in ${file_list}; do
	/opt/csw/bin/perl packaging/common/substitute.pl \
            ${pkg_root}/${file}.src \
            ${pkg_root}/${file} || exit 1
    done
    chmod ug+x ${pkg_root}/*/pre* ${pkg_root}/*/post*
}

do_build() {
    # Run for each server and client package.  .pkg files don't get whacked.
    # $1 must be "client" or "server"
    [ x"$1" = x"client" ] || [ x"$1" = x"server" ] || \
	{ echo "client or server not given" && exit 1; }
    rm -rf ${INSTALL_DEST} ${PKG_DEST}
    mkdir ${INSTALL_DEST} ${PKG_DEST} || exit 1
    ${MAKE} ${silent_make_flags} distclean
    echo "Running configure.."
    CONF="$CONF \
	STAR=/opt/csw/bin/star \
	GNUTAR=/opt/csw/bin/gtar \
	--quiet \
	--with-user=amandabackup \
	--with-group=disk \
	--prefix=/${PREFIX} \
	--exec-prefix=/${PREFIX} \
	--sbindir=/${PREFIX}/sbin \
	--sysconfdir=/${ETCDIR} \
	--with-amandates=/${ETCDIR}/amandates \
	--mandir=/${PREFIX}/share/man \
	--with-amlibexecdir=/${amlibdir}/amanda \
	--with-amperldir=/${amlibdir}/amanda/perl \
	--localstatedir=/${LOCALSTATEDIR} \
	--with-amdatadir=/${AMSTATEDIR} \
	--with-gnutar-listdir=/${AMSTATEDIR}/gnutar-lists \
	--with-index-server=localhost \
	--with-tape-server=localhost \
	--with-fqdn \
	--with-bsd-security \
	--with-bsdtcp-security \
	--with-bsdudp-security \
	--with-udpportrange=800,840 \
	--with-tcpportrange=11000,11040 \
	--with-low-tcpportrange=800,840 \
	--with-ssh-security \
	--with-debugging=/${DBGDIR} \
	--with-assertions \
	--with-readline \
	--disable-installperms \
	--disable-syntax-checks \
        --disable-static"

    # PKG_CONFIG_PATH was exported, so is in the environment.
    ./configure CFLAGS="${CFLAGS}" \
	CPPFLAGS="${CPPFLAGS}" \
	LDFLAGS="${LDFLAGS}" \
        GLIB_CFLAGS="${GLIB_CFLAGS}" \
        GLIB_LIBS="${GLIB_LIBS}" \
        GLIB_GENMARSHAL=glib-genmarshal \
        GOBJECT_QUERY=gobject-query \
        GLIB_MKENUMS=glib-mkenums \
	MAKE=${MAKE} \
	${CONF} || exit 1

    echo "Building $1.."

    # rpcgen should be run natively on solaris, linux generated XDR stubs
    # are not compatible. Specially when being compiled in 64 bit mode.
    # Ideally this should be part of Make.

    (cd ndmp-src;rm -f ndmp?_xdr.c)

    ${MAKE} ${silent_make_flags}|| exit 1
    ${MAKE} ${silent_make_flags} DESTDIR=${INSTALL_DEST} install || exit 1

    # the gnulib makefiles create $amlibdir/charset.alias in hopes of "merging"
    # it with a similar file from other applications.  This doesn't work with
    # DESTDIR, and anyway Amanda doesn't need this kind of fanciness because it
    # doesn't really use gettext.  So we just kill the file.  See bug 10955 for
    # more detail.
    rm -f ${INSTALL_DEST}/${amlibdir}/charset.alias

    # Create gnutar-lists
    mkdir ${INSTALL_DEST}/${PREFIX}/gnutar-lists

    echo "Amanda Enterprise Edition - version ${VERSION}" > ${INSTALL_DEST}/${PREFIX}/amanda-release || exit 1
}

do_package() {
    # First parameter is the subpkg, in all lower case.
    subpkg=${1}
    gnu_triplet=`/bin/sh ${src_dir}/config/config.guess`
    # Some but not all solaris packages have arch-plat-os dependent depend
    # files.
    if [ -f ${src_dir}/${pkg_root}/${subpkg}/depend-${gnu_triplet} ]; then
	# Move the arch-plat-os specific depend file to "depend"
	mv ${src_dir}/${pkg_root}/${subpkg}/depend-${gnu_triplet} \
	   ${src_dir}/${pkg_root}/${subpkg}/depend || exit 1
	# Delete extra depend-${gnu_triplet} files
	rm ${src_dir}/${pkg_root}/${subpkg}/depend-*
    fi
    cp ${src_dir}/${pkg_root}/${subpkg}/* ${PKG_DEST} || exit 1
    cd ${INSTALL_DEST} || exit 1

    # amanda does not create /etc/amanda
    mkdir -p ${AMSTATEDIR} || exit 1
    mkdir -p ${ETCDIR}/amanda || exit 1

    # Add the contents of 'pkgproto' along with all installed files to
    # 'prototype'.  pkgproto will generate file list for provided base
    # directories including the base dir. Including base dir in the pkg should
    # be avoided as the pkg installation will try to alter the base directory
    # permissions and ownership per pkg settings if included.
    cat "${PKG_DEST}/pkgproto" \
	>> ${PKG_DEST}/prototype || exit 1
    pkgproto $PREFIX ${AMSTATEDIR} ${ETCDIR}/amanda >> ${PKG_DEST}/prototype || exit 1

    # Using --disable-installperms creates installperms.sh, which this bit of
    # perl will merge into the prototype.  Note that this perl script is
    # perl-5.4 compatible
    cat > "${src_dir}/process_proto" <<'EOF'
use strict;
# make a hash from installperms
open(INSTPERM, "<" . shift @ARGV) or die("open installperms.sh: $!");
my %installperms = map {
    my ($u, $xtra, $g, $m, $fn) = ($_ =~ /^installperm "([^:"]+)(:?([^:"]+))?" "([^"]*)" "(.*)"/);
    $fn =~ s{^/}{}; # pkgproto has files without the leading slash
    ($fn, [ $u, $g, $m ]);
} <INSTPERM>;
# set user/group/mode from installperms, defaulting to amandabackup:disk
open(PROTO, "<" . shift @ARGV) or die("open proto: $!");
for my $line (<PROTO>) {
    if ($line !~ /^[df]/) {
        print $line;
        next;
    }
    my ($type, $class, $file, $mode, $user, $group) = split(/ /, $line);
    # default to amandabackup:disk, without changing mode
    ($user, $group) = ( "amandabackup", "disk" );
    if (exists $installperms{$file}) {
	my ($u, $g, $m) = @{$installperms{$file}};
	$user = $u if $u;
	$group = $g if $g;
	$mode = $m if $m;
    }
    print "$type $class $file $mode $user $group\n";
}
EOF

    perl "${src_dir}/process_proto" \
	"${src_dir}/installperms.sh" \
	"${PKG_DEST}/prototype" \
	> "${PKG_DEST}/prototype~" || exit 1
    mv "${PKG_DEST}/prototype~" "${PKG_DEST}/prototype"

    # Look for installed files in ${INSTALL_DEST}, send package to ${PKG_DEST}
    pkgmk -r ${INSTALL_DEST} -o -f ${PKG_DEST}/prototype -d ${PKG_DEST} \
	|| exit 1
    # pkgtrans puts the package back in our src_dir, where I would expected
    # it, and "translates" it into a .pkg file at the same time.

    pkgtrans -s ${PKG_DEST} ${src_dir}/AMANamanda-${subpkg}-${VERSION}-${gnu_triplet}.pkg<<EOF

EOF
    cd ${src_dir} || exit 1

}

src_dir=`pwd`

get_version
do_substitution

PKG_TMP=`pwd`/pkg_${VERSION}; export PKG_TMP
INSTALL_DEST=${PKG_TMP}/install; export INSTALL_DEST
PKG_DEST=${PKG_TMP}/pkg; export PKG_DEST

# Explanation of solaris paths:
# /opt/SUNWspro/*: Sun compiler, NOT USED FOR PACKAGING.
# /opt/csw/*: OpenCSW.
# /usr/ccs/*: sun compilation tools (ld, lex, yacc)
# /usr/sfw/*: SunFreeware, sometimes. (solaris 10)
# /usr/local/*: SunFreeware, othertimes. (solaris 8)

# sparc or intel
arch=`uname -p`
# 5.8 or 5.10
os_rel=`uname -r`

rm -rf ${PKG_TMP}
mkdir ${PKG_TMP} || exit 1

PATH=/opt/csw/bin:/usr/bin:/usr/sbin:/usr/ccs/bin;export PATH
# Compile 32bit because csw perl is 32bit and native is too old.
CFLAGS="-O2 -pipe -m32"; export CFLAGS
CPPFLAGS="-I/opt/csw/include"; export CPPFLAGS
# Not Absolute!  Remember to prefix a "/" except in pkgproto.
PREFIX=opt/amanda; export PREFIX # Not absolute.
amlibdir=${PREFIX}/lib     # Not absolute
LOCALSTATEDIR=var; export LOCALSTATEDIR
AMSTATEDIR=${LOCALSTATEDIR}/lib/amanda; export AMSTATEDIR
ETCDIR=etc; export ETCDIR
DBGDIR=${LOCALSTATEDIR}/log; export DBGDIR
# Each client and server and platform combination gets different compile options
if [ "x${1}" = "xclient" ] || [ "x${1}" = "x" ]; then
    CC=/usr/sfw/bin/gcc
    # Variables with spaces must be entered on the configure line separate from
    # CONF to maintain quoting.
    LDFLAGS="-L/usr/lib -R/usr/lib \
	-L/opt/csw/lib -R/opt/csw/lib \
        -Wl,-z,ignore"; export LDFLAGS
    PKG_CONFIG_PATH="/usr/lib/pkgconfig"; export PKG_CONFIG_PATH
    if [ "x$arch" = "xsparc" -a "x$os_rel" = "x5.10" ]; then
        # Use explicit flags for GLIB, because pkgconfig provides flags
        # for SunStudio compiler (not compatible with gcc).
        GLIB_CFLAGS="-I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include"; export GLIB_CFLAGS
        GLIB_LIBS="-lglib-2.0 -lgobject-2.0 -lgthread-2.0"; export GLIB_LIBS
    elif [ "x$arch" = "xi386" -a "x$os_rel" = "x5.10" ]; then
        GLIB_CFLAGS="-I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include"; export GLIB_CFLAGS
        GLIB_LIBS="-lglib-2.0 -lgobject-2.0 -lgthread-2.0"; export GLIB_LIBS
    elif [ "x$arch" = "xsparc" -a "x$os_rel" = "x5.8" ]; then
        # CSW glib2.0 flags for gcc.  CSW compiles with Sunstudio, so some
        # flags may not work
        GLIB_CFLAGS="-I/opt/csw/include/glib-2.0 -I/opt/csw/lib/glib-2.0/include"; export GLIB_CFLAGS
        GLIB_LIBS="-lglib-2.0 -lintl -lgobject-2.0 -lgthread-2.0"; export GLIB_LIBS
	CC="/usr/local/bin/gcc"
    fi
    CONF="--with-amlibdir=/${amlibdir} \
	--without-server \
	--disable-s3-device \
	CC=$CC \
	PERL=/opt/csw/bin/perl"; export CONF

    do_build "client"
    do_package "client"
fi

if [ "x${1}" = "xserver" ] || [ "x${1}" = "x" ]; then
    LDFLAGS="-L/usr/lib -R/usr/lib \
        -L/opt/csw/lib -R/opt/csw/lib \
        -L/usr/sfw/lib \
        -Wl,-z,ignore"; export LDFLAGS
    PKG_CONFIG_PATH="$PKG_CONFIG_PATH:/usr/lib/pkgconfig:/opt/csw/lib/pkgconfig"; export PKG_CONFIG_PATH
    if [ "x$arch" = "xsparc" -a "x$os_rel" = "x5.10" ]; then
        # Use explicit flags for GLIB, because pkgconfig provides flags
        # for SunStudio compiler (not compatible with gcc).
        GLIB_CFLAGS="-I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include"; export GLIB_CFLAGS
        GLIB_LIBS="-lglib-2.0 -lgobject-2.0 -lgthread-2.0"; export GLIB_LIBS
    elif [ "x$arch" = "xi386" -a "x$os_rel" = "x5.10" ]; then
        GLIB_CFLAGS="-I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include"; export GLIB_CFLAGS
        GLIB_LIBS="-lglib-2.0 -lgobject-2.0 -lgthread-2.0"; export GLIB_LIBS
    elif [ "x$arch" = "xsparc" -a "x$os_rel" = "x5.8" ]; then
	msg="We don't support server on Solaris 5.8."
	# if we were run with no arguments, then this is not an error, just a warning
	if [ "x${1}" = "x" ]; then
            echo "Note: $msg"
	    exit 0
	else
            echo "Error: $msg"
	    exit 1
	fi
    fi
    CONF="--with-amlibdir=/${amlibdir} \
	--enable-s3-device \
        --with-libcurl=/opt/csw \
	CC=/usr/sfw/bin/gcc \
	PERL=/opt/csw/bin/perl \
	MTX=/opt/csw/sbin/mtx" ; export CONF

    do_build "server"
    do_package "server"
fi
